package com.apes.fn.server.productRequire;

import com.apes.fn.mdm.purchase.PurchasingGroup;
import com.apes.fn.tms.model.Site;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ProductRequireItem.CONST_TABLE_NAME)
public class ProductRequireItem extends BaseModel {

    public static final String CONST_TABLE_NAME = "stock_product_require_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, padding = 1, name = "要货单明细")
    private String id; // 唯一编码


    @ManyToOne(optional = false)
    @JoinColumn(name = "product_require_id", referencedColumnName = "id", nullable = false)
    @Comment("订单")
    private ProductRequire productRequire;

    @ManyToOne(optional = false)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    /***
     * 通过公司(服务单) 品类 品牌查询统采范围
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    @Comment("采购组织编码")
    private Dept deptId;  //采购组织


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", referencedColumnName = "id", nullable = false)
    @Comment("商品")
    private Product product;

    @Transient
    private String instruction; // 包装说明

    public String getInstruction() {
        if( product == null ) return null;
        return product.getInstruction();
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id", nullable = false)
    @Comment("计量单位")
    private ProductUom uom;


    @Column(name = "qty_require", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("要货数量")
    private double qtyRequire = 0;


    @Column(name = "remark", length = 120)
    @Comment("备注")
    private String remark;

    public void addRemark(String msg) {
        if( remark != null && !remark.equals("") ) {
            this.remark = this.remark + ";" + msg;
        } else {
            this.remark = msg;
        }
    }

    @Column(name = "qty_assigned", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("已分配数量")
    private double qtyAssigned = 0;


    @Column(name = "qty_ended", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("已终止数量")
    private double qtyEnded = 0;

    public void addQtyEnded(Double qty){
        // 不做验证缺乏老框架的数据，例如采购计划数量 
        if (this.qtyEnded + qty > this.getQtyRequire())
            throw new RuntimeException("可终止数量为：" + (this.getQtyRequire() - this.getQtyAssigned() - this.orderQty - this.getQtyEnded()) + this.uom.getName() + ", 商品：" + this.getProduct().getId());
        this.qtyEnded = this.qtyEnded + qty;
    }

    @Transient
    private double qtyEnd = 0; // 本次终止件数

    @Column(name = "qty_purchase", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("采购数量")
    private double qtyPurchase = 0;

    @Column(name = "qty_arrive", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("实际到货数量")
    private double qtyArrive = 0;

    @Column(name = "order_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("制单数量")
    private double orderQty;

    @Column(name = "arrive_date")
    @Comment("实际到货日期")
    private Date arriveDate;

    @Column(name = "commodity_inquiry_order_id")
    @Comment("询价单号")
    private String commodityInquiryOrderId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "termination_reson", referencedColumnName = "id")
    @Comment("终止原因")
    private Enumeration terminationReson;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商编码")
    private PartyRole supplier;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "site_id", referencedColumnName = "id")
    @Comment("站点")
    private Site site;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "purchasing_group_id", referencedColumnName = "id")
    @Comment("采购组")
    private PurchasingGroup purchasingGroup;

    @Column(name = "expected_arrival_time", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("预计到货时长")
    private double expectedArrivalTime = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "source_state", referencedColumnName = "id" )
    @Comment("货源状态")
    private Enumeration sourceState;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "logistics_mode_id", referencedColumnName = "id")
    @Comment("物流方式")
    private Enumeration logisticsMode;

    @Column(name = "channel_type", columnDefinition = "number(2)")
    @Comment("渠道类型")
    private Integer channelType;//1:价格前置 //2:新平台询价//3：询价执行表

    @Column(name = "sp_id")
    @Comment("供应商平台商品ID")
    private String spId;

    @Column(name = "offer_id", length = 4000)
    @Comment("报价ID")
    private String offerId;

    @Column(name = "unique_value", length = 4000)
    @Comment("唯一值")
    private String uniqueValue;

    @Column(name = "error_Message", length = 2000)
    @Comment("供应商下订单错误信息")
    private String errorMessage;

    @OneToOne(mappedBy = "requireItem", cascade = CascadeType.ALL)
    private RequireInquireItem requireInquireItems;
    public RequireInquireItem getRequireInquireItems() {
        if (requireInquireItems != null) {
            requireInquireItems.setRequireItem(this);
        }
        return requireInquireItems;
    }

/*    public Enumeration getSourceState() {
        if (StringUtils.hasText(this.getProductRequire().getSource())) return this.sourceState;
        return SpringManager.getBean(EnumerationRepository.class).findOne("003334");
    }*/
    /**
     * 该明细行是否全部终止
     * @return
     */
    public boolean checkEnd(){
        if(this.qtyRequire == this.qtyEnded) return true;
        return false;
    }

    public double canEndQty(){
        return this.qtyRequire - this.qtyAssigned - this.qtyEnded - this.orderQty;
    }


    public double getCurrentAssigentQty(double currentAssigentMinFactorQty) {
        double currentResidue = this.getQtyRequire() - this.getQtyAssigned();
        if (currentResidue < 0) {
            return 0;
        } else if (currentResidue >= currentAssigentMinFactorQty) {
            return currentAssigentMinFactorQty;
        } else if (currentResidue < currentAssigentMinFactorQty) {
            return currentResidue;
        } else {
            throw new RuntimeException("计算可减分配数量异常");
        }
    }

    public double currentStopQty(double currentStopMinFactorQty) {
        if (this.getQtyRequire() > this.getQtyAssigned()) {
            return currentStopMinFactorQty;
        } else if (this.getQtyAssigned() - currentStopMinFactorQty > this.getQtyRequire()) {
            return 0;
        }
        return this.getQtyRequire() - (this.getQtyAssigned() - currentStopMinFactorQty);
    }
}
